package com.hsmpay.mobile.action.account;

import com.hsmpay.common.pojo.user.User;
import com.hsmpay.mobile.action.trans.TransBaseAction;
import com.hsmpay.mobile.pojo.system.Holidays;
import com.hsmpay.mobile.pojo.trans.TransOrder;
import com.hsmpay.mobile.pojo.user.UserMoney;
import com.hsmpay.mobile.pojo.user.UserTransLimit;
import com.hsmpay.mobile.service.account.CashMoneyService;
import com.hsmpay.mobile.service.system.HolidaysService;
import com.hsmpay.mobile.service.user.UserMoneyService;
import com.hsmpay.mobile.service.user.UserTransLimitService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 账务  提现action
 *
 * @author 颜铃璋
 * @date 2012-1-17
 */
@Controller("cashMoneyAction")
@Scope("prototype")
public class CashMoneyAction extends TransBaseAction {
    private static final long serialVersionUID = -4209437170500467527L;
    private static Logger log = Logger.getLogger(CashMoneyAction.class);

    @Resource(name = "cashMoneyService")
    private CashMoneyService<TransOrder, Long> cashMoneyService;
    @Resource(name = "userMoneyService")
    private UserMoneyService<UserMoney, Long> userMoneyService;
    //交易限制服务
    @Resource(name = "userTransLimitService")
    private UserTransLimitService<UserTransLimit, Long> userTransLimitService;
    @Resource(name = "holidaysService")
    private HolidaysService<Holidays, Long> holidaysService;

    private int clientType;//客户端类型
    private long terminalTypeId;//终端类型
    private long roleId;//终端角色
    private Double money;

    static double maxCashMoney = 0.0;//最大提现金额
    static double minCashMoney = 0.0;//最小提现金额
    static double cashMoneyFeeRate = 0.002;//手续费 费率
    static Double maxFeeMoney = 0.0;//封顶手续费  0 不封顶
    static Double minFeeMoney = 2.0;//最小手续费
    static double totalMaxCashMoney = 0.0;//当日最高提现金额  0 为没有限额
    static int limitNum = 0;//限制 笔数

    /**
     * 提现
     *
     * @return
     * @throws Exception
     */
    public String cashMoney() throws Exception {
        log.debug("--- picUpload() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));
        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        if (js.containsKey("money"))
            money = Double.parseDouble(js.getString("money"));
        if (js.containsKey("functionKey"))
            functionKey = js.getString("functionKey");
        functionKey = "CASHMONEY";
        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("userId = " + userId);
        log.debug("money = " + money);
        log.debug("functionKey = " + functionKey);

        if (null == userId) {
            log.info("提现时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (null == money) {
            log.info("提现时, 传入参数money为空");
            sendAppErrorMsg("6001", "money");
            return null;
        }
        if (StringUtils.isBlank(functionKey)) {
            log.info("提现时, 传入参数functionKey为空");
            sendAppErrorMsg("6001", "functionKey");
            return null;
        }

        try {
            //直接  屏蔽  该接口
            if (true) {
                String message = encryptAppMsg(0, "LS99", "尊敬的用户您好，您的版本过低，请升级最新软件进行提现！！");
                sendAppMsg(message);
                return null;
            }


            Date date = new Date();
            if (!checkTime(date)) {//检测时间
                return null;
            }

            if (!checkPIV(functionKey)) {
                log.warn("提现时, 银行接口暂停使用！");
                return null;
            }
            /*if(money > maxCashMoney){
				log.info("提现错误，提现金额不能大于"+maxCashMoney+" 元！");
				sendAppErrorMsg("6080", maxCashMoney+"");
				return null;
			}*/
            if (money <= minCashMoney) {
                log.info("提现错误，提现金额不能小于" + minCashMoney + " 元！");
                sendAppErrorMsg("6081", minCashMoney + "");
                return null;
            }

            User user = userService.getUserById(userId);
            if (null != user) {
                //判断 绑定银行卡
                if (null == user.getBankStatus() || 3 == user.getBankStatus()) {
                    sendAppErrorMsg("6041");
                    return null;
                } else if (2 == user.getBankStatus()) {
                    sendAppErrorMsg("6042");
                    return null;
                } else if (0 == user.getBankStatus()) {//0:认证失败 1:认证通过 2:审核中 3:未申请认证 DEFAULT 3
                    sendAppErrorMsg("6043");
                    return null;
                }


                //查询用户余额  是否满足提现
                double fee = getFee(money);
                double tempMoney = money + fee;
                //查询用户虚拟货币
				/*UserMoney userMoney = new UserMoney();
				userMoney.setUserId(userId);
				userMoney = userMoneyService.searchEntity(userMoney);*/
                //金额是否足够
                boolean isZhugou = userMoneyService.moneyTheAdequacy(userId, tempMoney, 1);
                if (!isZhugou) {
                    log.info("提现错误，金额不足！");
                    sendAppErrorMsg("6082", tempMoney + "");
                    return null;
                }
                //提现总金额超限
				/*boolean isMaxCashMoneyLimit = transLimitService.cashMoneyTotalMoneyLimit(userId,money,totalMaxCashMoney);
				if(isMaxCashMoneyLimit){
					log.info("提现错误，您今天提现总金额超限！");
					sendAppErrorMsg("6085", totalMaxCashMoney+"");
					return null;
				}*/

                //Date date = new Date();
                TransOrder transOrder = new TransOrder();
                transOrder.setOrderNum(getOrderNumByDate(date));
                transOrder.setOrderTypeId(8l);//提现
                transOrder.setUserId(userId);
                transOrder.setTransMoney(money);

                transOrder.setFeeMoney(fee);//fee);//手续费
                transOrder.setBrokerage(0.0000);//brokerage);
                transOrder.setDealerBrokerage(0.0000);
                transOrder.setChargeAmount(money);
                transOrder.setRootCategory("账务管理");
                transOrder.setCategory("提现");
                //transOrder.setName();//user.getUserName());//付款方
                //transOrder.setBankCard(user.getBankCard());
                //transOrder.setOpeningBank(user.getOpeningBank());//"农业银行");//);
                transOrder.setObjectiveName(user.getCardholder());//对方姓名
                transOrder.setObjectiveCard(user.getBankCard());//对方银行卡
                transOrder.setObjectiveOpBank(user.getOpeningBank());//对方银行
                transOrder.setStatus(2);//交易状态  0交易失败 1交易成功 2银行交易处理中 3 未付款 4等待对方付款5关闭交易
                transOrder.setClearing(0);//结算状态 0未结算 1结算
                transOrder.setDescription("系统结算");//交易详情
                transOrder.setCreateDate(date);
                transOrder.setUpdateLongTime(date.getTime());

                //transOrder.setBranchesBank(cashMoney.getBranchesBank());//用户银行支行
                //transOrder.setBBankProvince(cashMoney.getBBankProvince());
                //transOrder.setBBankCity(cashMoney.getBBankCity());
                //transOrder.setMobile(cashMoney.getMobile());//用户 手机号
                transOrder.setObjectiveBBank(user.getBranchesBank());//对方。银行支行
                transOrder.setObjectiveBBProvince(user.getBBankProvince());
                transOrder.setObjectiveBBCity(user.getBBankCity());
                transOrder.setObjectiveMobile(user.getMobile());//对方手机号
                transOrder.setObjectiveBBankCode(user.getBranchesBankCode());
                //三毛接口 银行代码
                transOrder.setObjectiveAccBankCode(user.getAccBankCode());
                transOrder.setTerminalTypeId(terminalTypeId);
                transOrder.setRoleId(roleId);

                transOrder.setFeeRate(user.getFeeRate());//用户费率
                transOrder.setFdMaxFee(user.getFdMaxFee());//用户封顶最高
                transOrder.setFdMinFee(user.getFdMinFee());//用户封顶最低
                //判断 机构预存款
                int flag = cashMoneyService.cashMoney(transOrder);

                if (flag == 1) {
                    Map<String, Object> result = new LinkedHashMap<String, Object>();
                    result.put("reqCode", "0000");
                    result.put("reqMsg", "提现成功，一小时内自动结算到您绑定的银行卡账号中！");
                    sendAppMsg(result);
                } else if (flag == 2) {//预存款不足
                    sendAppErrorMsg("6084");
                }
            } else {
                log.warn("提现时, 用户Id=" + userId + " 对应的用户不存在!");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }

    /**
     * 提现检测
     *
     * @return
     * @throws Exception
     */
    public String checkCashMoney() throws Exception {
        log.debug("--- checkCashMoney() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));

        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        functionKey = "CASHMONEY";

        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("userId = " + userId);
        log.debug("functionKey = " + functionKey);
        if (null == userId) {
            log.info("提现时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (StringUtils.isBlank(functionKey)) {
            log.info("提现时, 传入参数functionKey为空");
            sendAppErrorMsg("6001", "functionKey");
            return null;
        }

        try {
            //直接  屏蔽  该接口
            if (true) {
                String message = encryptAppMsg(0, "LS99", "尊敬的用户您好，您的版本过低，请升级最新软件进行提现！！");
                sendAppMsg(message);
                return null;
            }


            Date date = new Date();
            if (!checkTime(date)) {//检测时间
                return null;
            }

            if (!checkPIV(functionKey)) {
                log.warn("提现时, 银行接口暂停使用！");
                return null;
            }

            //判断 用户提现限制
            boolean isLimit = userTransLimitService.cashMoneyNumberLimit(userId, limitNum);
            if (isLimit) {
                log.info("提现错误，提现次数达到上限!");
                sendAppErrorMsg("6083");
                return null;
            }

            Map<String, Object> result = new LinkedHashMap<String, Object>();

            result.put("maxCashMoney", maxCashMoney);//最高提现
            result.put("minCashMoney", minCashMoney);//最低提现
            result.put("cashMoneyFeeRate", cashMoneyFeeRate);//手续费费率
            result.put("maxFeeMoney", maxFeeMoney);//封顶手续费 0.0 不封顶
            result.put("minFeeMoney", minFeeMoney);//最低手续费
            result.put("totalMaxCashMoney", totalMaxCashMoney);//当日最高 提现金额
            result.put("reqCode", "0000");
            result.put("reqMsg", "提现检测成功！");
            sendAppMsg(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }


    private double getFee(double money) {
        Double fee = money * cashMoneyFeeRate;
        if (fee < minFeeMoney) {
            fee = minFeeMoney;
        }
        if (maxFeeMoney != 0.0 && fee > maxFeeMoney) {
            fee = maxFeeMoney;
        }
        return fee;
    }

    /**
     * 检测时间
     *
     * @return
     * @throws Exception
     */
    private boolean checkTime(Date date) throws Exception {
        if (holidaysService.isHolidays(date)) {
            String message = encryptAppMsg(0, "LS03", "尊敬的用户您好，节假日提现功能不提供服务，给您带来的不便敬请谅解！");
            sendAppMsg(message);
            return false;
        }

        if (holidaysService.isWeekend(date) && !holidaysService.isLegalWorkDay(date)) {
            String message = encryptAppMsg(0, "LS02", "尊敬的用户您好，周六周日提现功能不提供服务，给您带来的不便敬请谅解！");
            sendAppMsg(message);
            return false;
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (cal.get(Calendar.HOUR_OF_DAY) < 9 || cal.get(Calendar.HOUR_OF_DAY) >= 18) {
            String message = encryptAppMsg(0, "LS01", "尊敬的用户您好，提现功能只在工作日的 9:00 —— 18:00 时间内提供服务！");
            sendAppMsg(message);
            return false;
        }
        return true;
    }

    public static void main(String args[]) {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        log.debug(cal.get(Calendar.HOUR_OF_DAY));
    }
}
